import { Body, Controller, Get, Post, Query } from "@nestjs/common";
import { CreateItemDto, Item, PaginationQuery } from "./app.dto";
import { AppService } from "./app.service";
import { Roles } from "./decorators/roles.decorator";
import { faker } from "./faker";
import { NonResult } from "./decorators/non-result.decorator";

@Controller()
export class AppController {
	private readonly items: Item[] = [];

	constructor(private readonly appService: AppService) {
		for (let i = 0; i < 100; i++) {
			this.items.push({
				id: i + 1,
				name: faker.person.fullName(),
				age: faker.number.int({ min: 12, max: 60 }),
				email: faker.internet.email(),
				mobile: faker.phone.number({ style: "international" }),
				introduction: faker.person.bio(),
			});
		}
	}

	@Get()
	getHello(): string {
		return this.appService.getHello();
	}

	@Get("non-result")
	@NonResult()
	getNonResult(): string {
		return "This endpoint does not return a Result type.";
	}

	@Roles("manager")
	@Get("items")
	getItems(@Query() searchModel?: PaginationQuery): Item[] {
		let items = this.items;
		if (!searchModel) {
			return items;
		}
		const { searchText, pageIndex, pageSize } = searchModel;
		if (searchText) {
			items = items.filter((item) => item.name.includes(searchText));
		}
		items = items.slice((pageIndex! - 1) * pageSize!, pageIndex! * pageSize!);
		return items;
	}

	@Roles("admin")
	@Post("items")
	createItem(@Body() dto: CreateItemDto): number {
		const newItem: Item = { ...dto, id: this.items.length + 1 };
		this.items.push(newItem);
		return newItem.id;
	}
}
